package model

import (
	"fmt"
	"time"

	"gitee.com/goframe/lt-collector/libs/libce"
	"gitee.com/goframe/lt-collector/libs/orma"
)

func (m *GameLotteries) GetLatestOpenData() (openData *OpenData, err error) {
	ce := libce.NewMemoryCache()
	cacheKey := fmt.Sprintf("lottoLatestOpenData:%d", m.ID)
	val, has := ce.Get(cacheKey)
	if has {
		openData = val.(*OpenData)
	} else {
		openData = new(OpenData)
		err = orma.NormalGet(openData.Session().Where("gid=?", m.ID).
			Desc("open_timestamp").Limit(1).Get(openData))
		if err != nil {
			return
		}
		openData.LotName = m.Name
		openData.LotNameCN = m.NameCN
		ce.Set(cacheKey, openData, time.Second*1)
	}
	return
}

//OpenInfo 获取开奖信息数据... 带缓存
func (m *GameLotteries) OpenInfo() (openData *OpenData, err error) {
	gid := m.ID
	ce := libce.NewMemoryCache()
	cacheKey := fmt.Sprintf("lottoBaseOpenInfo:%d", gid)
	val, has := ce.Get(cacheKey)
	if has {
		openData = val.(*OpenData)
	} else {
		plan := new(GameIssuePlan)
		err = orma.NormalGet(plan.Session().Where("gid=?", gid).Get(plan))
		if err != nil {
			return
		}
		openData, err = plan.ParseIssueAndTime()
		if err != nil {
			return
		}
		err = orma.NormalGet(openData.Session().
			Where("gid=? and issue=?", gid, openData.Issue).
			NoAutoCondition().Get(openData))
		if err == orma.ErrOrmNotFound {
			err = nil
		}
		if err != nil {
			return
		}
		openData.LotName = m.Name
		openData.LotNameCN = m.NameCN
		ce.Set(cacheKey, openData, time.Second*2)
	}
	return
}
